import SwiftUI
import AppKit

struct GameView: View {
    @ObservedObject var viewModel: GameViewModel
    private let cellSize: CGFloat = 30
    private let gridSpacing: CGFloat = 2
    
    // 计算窗口所需的最小宽度
    private var minWindowWidth: CGFloat {
        let gridWidth = CGFloat(viewModel.currentConfig.width) * (cellSize + gridSpacing)
        let sidebarWidth: CGFloat = 200  // 右侧边栏宽度
        let padding: CGFloat = 40  // 两侧内边距
        return gridWidth + sidebarWidth + padding
    }
    
    // 计算窗口所需的最小高度
    private var minWindowHeight: CGFloat {
        let gridHeight = CGFloat(viewModel.currentConfig.height) * (cellSize + gridSpacing)
        let statusBarHeight: CGFloat = 80  // 状态栏高度
        let padding: CGFloat = 40  // 上下内边距
        return gridHeight + statusBarHeight + padding
    }
    
    var body: some View {
        HStack(spacing: 20) {
            // 左侧主游戏区域
            VStack(spacing: 16) {
                gameStatusView
                    .frame(maxWidth: .infinity)
                gameGrid
                    .frame(maxWidth: .infinity)
            }
            .frame(maxWidth: .infinity, alignment: .center)
            
            // 右侧控制区域
            VStack(spacing: 20) {
                Spacer()
                operationGuide
                controlButtons
                Spacer()
            }
            .frame(width: 200)  // 固定右侧边栏宽度
        }
        .padding()
        .frame(width: minWindowWidth, height: minWindowHeight)
        .animation(.easeInOut(duration: 0.3), value: viewModel.currentDifficulty)
        .alert("游戏结束", isPresented: $viewModel.showAlert) {
            Button("新游戏", action: viewModel.newGame)
        } message: {
            Text(viewModel.currentGameState == .won ? "胜利！" : "踩到地雷！")
        }
    }
    
    private var gameStatusView: some View {
        HStack {
            VStack(alignment: .leading) {
                Text("总雷数: \(viewModel.currentConfig.mines)")
                    .font(.caption)
                    .foregroundColor(.secondary)
                Text("剩余: \(viewModel.currentConfig.mines - viewModel.flaggedCount)")
                    .font(.title2)
                    .foregroundColor(.red)
            }
            Spacer()
            VStack {
                Button(action: viewModel.newGame) {
                    Image(systemName: "face.smiling")
                        .font(.system(size: 28))
                        .foregroundColor(.yellow)
                }
                .buttonStyle(.plain)
            }
            Spacer()
            VStack(alignment: .trailing) {
                Text("时间")
                    .font(.caption)
                    .foregroundColor(.secondary)
                Text(String(format: "%03d", viewModel.elapsedSeconds))
                    .font(.title2)
                    .foregroundColor(.green)
            }
            
            VStack(alignment: .trailing) {
                Text("已标记")  
                    .font(.caption)
                    .foregroundColor(.secondary)
                Text("\(viewModel.flaggedCount)")
                    .font(.title2)
                    .foregroundColor(.blue)
            }
            
            VStack(alignment: .trailing) {
                Text("最后标记")
                    .font(.caption)
                    .foregroundColor(.secondary)
                Text(viewModel.lastFlaggedCoordinate != nil ? 
                     "X:\(viewModel.lastFlaggedCoordinate!.x) Y:\(viewModel.lastFlaggedCoordinate!.y)" : "无")
                    .font(.title2)
                    .foregroundColor(.purple)
            }
        }
        .padding()
        .background(Color.gray.opacity(0.2))
        .cornerRadius(10)
    }
    
    private var operationGuide: some View {
        VStack(alignment: .leading, spacing: 4) {
            HStack(spacing: 20) {
                VStack(alignment: .leading) {
                    Text("鼠标操作：")
                        .font(.caption2)
                        .underline()
                    Text("左键单击 - 翻开格子")
                        .font(.caption2)
                    Text("右键单击 / ⌃+左键 - 标记地雷")
                        .font(.caption2)
                }
                VStack(alignment: .leading) {
                    Text("触控板操作：")
                        .font(.caption2)
                        .underline()
                    Text("单指点按 - 翻开格子")
                        .font(.caption2)
                    Text("长按 / 双指点按 - 标记地雷")
                        .font(.caption2)
                }
            }
        }
        .foregroundColor(.secondary)
        .padding()
        .background(Color.gray.opacity(0.1))
        .cornerRadius(8)
    }
    
    private var gameGrid: some View {
        LazyVGrid(columns: Array(repeating: GridItem(.fixed(cellSize), spacing: gridSpacing), 
                               count: viewModel.currentConfig.width),
                 spacing: gridSpacing) {
            ForEach(0..<viewModel.currentConfig.height, id: \.self) { y in
                ForEach(0..<viewModel.currentConfig.width, id: \.self) { x in
                    GameCellView(
                        cell: viewModel.boardCells[x][y],
                        coordinate: Coordinate(x: x, y: y),
                        viewModel: viewModel,
                        size: cellSize
                    )
                }
            }
        }
        .frame(width: CGFloat(viewModel.currentConfig.width) * (cellSize + gridSpacing),
               height: CGFloat(viewModel.currentConfig.height) * (cellSize + gridSpacing))
        .background(Color.gray.opacity(0.1))
        .cornerRadius(8)
    }
    
    private var controlButtons: some View {
        VStack(spacing: 20) {
            Button(action: { viewModel.changeDifficulty(difficulty: .beginner) }) {
                Text("初级（9×9）")
                    .font(.subheadline)
                    .padding(.vertical, 8)
                    .padding(.horizontal, 12)
                    .background(viewModel.currentDifficulty == .beginner ? Color.blue : Color.gray.opacity(0.3))
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
            .buttonStyle(.plain)
            
            Button(action: { viewModel.changeDifficulty(difficulty: .intermediate) }) {
                Text("中级（16×16）")
                    .font(.subheadline)
                    .padding(.vertical, 8)
                    .padding(.horizontal, 12)
                    .background(viewModel.currentDifficulty == .intermediate ? Color.blue : Color.gray.opacity(0.3))
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
            .buttonStyle(.plain)
            
            Button(action: { viewModel.changeDifficulty(difficulty: .expert) }) {
                Text("高级（30×16）")
                    .font(.subheadline)
                    .padding(.vertical, 8)
                    .padding(.horizontal, 12)
                    .background(viewModel.currentDifficulty == .expert ? Color.blue : Color.gray.opacity(0.3))
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
            .buttonStyle(.plain)
        }
        .padding(.top, 10)
    }
}
